from config import redis
from redis import StrictRedis
import json


def key_serializer(args):
    args = {k: v for k, v in args.items() if k not in args.keys()}
    return f'''{args}'''


class CustomRedisCache:
    def __init__(self, redis_client, key_serializer=None):
        self.redis_client = redis_client
        self.key_serializer = key_serializer or self._default_key_serializer

    def _default_key_serializer(self, args):
        return f'''{args}'''

    def cache(self, expire=3600):
        def decorator(func):
            def wrapper(*args, **kwargs):
                cache_key = self.key_serializer(kwargs)
                cached_value = self.redis_client.get(cache_key)

                if cached_value is not None:
                    return json.loads(cached_value)

                result = func(*args, **kwargs)
                self.redis_client.set(
                    cache_key,
                    json.dumps(result),
                    ex=expire
                )
                return result

            return wrapper

        return decorator


redis_client = StrictRedis(
    host=redis.host,
    port=redis.port,
    db=redis.db,
    password=redis.password,
    decode_responses=True)

cache = CustomRedisCache(redis_client=redis_client,
                         key_serializer=key_serializer)